package com.sum.tea.xinlian.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sum.tea.contants.AppConfig
import com.sum.tea.xinlian.bean.LEDParams
import com.sum.tea.xinlian.bean.TemperatureParams
import com.uhf.api.cls.R2000_calibration
import com.uhf.api.cls.Reader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.experimental.inv

class TagTempViewModel : ViewModel() {
    private var mAppConfig = AppConfig()
    private val _temperatureData = MutableLiveData<String?>()
    val temperatureData: LiveData<String?> = _temperatureData

    private val _ledData = MutableLiveData<String?>()
    val ledData: LiveData<String?> = _ledData

    private val _toastMessage = MutableLiveData<String?>()
    val toastMessage: LiveData<String?> = _toastMessage

    fun readTemperature(params: TemperatureParams) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val rpaswd = params.password.takeIf { it.isNotEmpty() }?.let {
                    ByteArray(4).also { arr ->
                        mAppConfig.Mreader.Str2Hex(arr.toString(), arr.size, arr)
                    }
                }
                val tagtemp = R2000_calibration().Tagtemperture_DATA()
                val er = mAppConfig.Mreader.ReadTagTemperature(
                    params.opant,
                    params.bank,
                    params.adrhex,
                    params.blkcnt,
                    params.readtimeout,
                    params.selwait,
                    params.readwait,
                    params.metaData.metaflag,
                    rpaswd,
                    tagtemp
                )
                val result = if (er == Reader.READER_ERR.MT_OK_ERR) {
                    StringBuilder().apply {
                        val tempData = tagtemp.Data()
                        append(if ((tempData[0].toInt() and 0x80) == 0) {
                            "${(tempData[0].toInt() and 0xff) - 45}.${(tempData[1].toInt() and 0xff) * 100 / 255}"
                        } else {
                            tempData[0] = (tempData[0].inv() + 1).toByte()
                            tempData[1] = tempData[1].inv().toByte()
                            "-${(tempData[0].toInt() and 0xff) - 45}.${(tempData[1].toInt() and 0xff) * 100 / 255}"
                        })
                        append(" ℃ EPC:${Reader.bytes_Hexstr(tagtemp.TagEpc())}")
                        if (params.metaData.IsReadCnt) append(" 次数:${tagtemp.ReadCount()}")
                        if (params.metaData.IsAntennaID) append(" 天线:${tagtemp.Antenna()}")
                        if (params.metaData.IsRSSI) append(" RSSI:${tagtemp.Lqi()}")
                        if (params.metaData.IsFrequency) append(" 频率:${tagtemp.Frequency()}")
                    }.toString()
                } else {
                    "failed:$er"
                }
                _temperatureData.postValue(result)
            } catch (e: Exception) {
                _toastMessage.postValue(AppConfig.Constr_excep + e.message)
            }
        }
    }

    fun startLEDTask(params: LEDParams) {
        viewModelScope.launch(Dispatchers.IO) {
            while (true) {
                val tagled = R2000_calibration().TagLED_DATA()
                val er = mAppConfig.Mreader.ReadTagLED(params.opant, params.readtimeout.toShort(), params.metaData.getMetaflag(), tagled)

                val result = if (er == Reader.READER_ERR.MT_OK_ERR) {
                    StringBuilder().apply {
                        append("EPC:${Reader.bytes_Hexstr(tagled.TagEpc())}")
                        if (params.metaData.IsReadCnt) append(" 次数:${tagled.ReadCount()}")
                        if (params.metaData.IsAntennaID) append(" 天线:${tagled.Antenna()}")
                        if (params.metaData.IsRSSI) append(" RSSI:${tagled.Lqi()}")
                        if (params.metaData.IsFrequency) append(" 频率:${tagled.Frequency()}")
                    }.toString()
                } else {
                    "failed:$er"
                }
                _ledData.postValue(result)
                delay(params.sleep.toLong())
            }
        }
    }

    fun stopLEDTask() {
        viewModelScope.coroutineContext.cancelChildren()
    }
}